#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project : aimix
@File    : video_deduplication_worker.py
@IDE     : PyCharm
@Author  : admin
@Date    : 2025/4/21 14:42
"""
import json
import traceback
from worker.base_worker import BaseThread
from multiprocessing import Process
from concurrent.futures import ThreadPoolExecutor, as_completed
from core.video.video_deduplication import VideoDeduplication


def do_work(items, progress_queue):
    video_deduplication = VideoDeduplication(
        input_files=items.get("input_files"),
        output_path=items.get("output_dir"),
        flip_status=items.get("flip_status"),
        speed_up_status=items.get("speed_up_status"),
        extract_frames_status=items.get("extract_frames_status"),
        add_img_overlay_status=items.get("add_img_overlay_status"),
        add_video_overlay_status=items.get("add_video_overlay_status"),
        adjust_video_status=items.get("adjust_video_status"),
        adjust_hsl_status=items.get("adjust_hsl_status"),
        adjust_color_balance_status=items.get("adjust_color_balance_status"),
        **items.get("kwargs")
    )
    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = []
        for args in items.get("input_files"):
            progress_queue.put(100//len(items.get("input_files"))/2)
            futures.append(executor.submit(video_deduplication.complete, args))
        for future in as_completed(futures):
            future.result()
            progress_queue.put(100//len(items.get("input_files"))/2)
    progress_queue.put("done")



class VideoDeduplicationQtThread(BaseThread):

    def __init__(self, content, parent=None):
        super(VideoDeduplicationQtThread, self).__init__(content, parent)
        self.content = content


    def run(self):
        try:
            self.process = Process(target=do_work, args=(self.content, self.queue))
            self.process.start()
            while True:
                msg = self.queue.get()
                if msg == "done":
                    break
                self.on_change_progress(msg)

        except Exception as e:
            traceback.print_exc()
            self.failed.emit(e)
